package com.ihighest.app.infox.fragment;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.ColumnNameActivity;
import com.ihighest.app.infox.activity.CompanyPagesActivity;
import com.ihighest.app.infox.activity.LoginActivity;
import com.ihighest.app.infox.activity.SubscriptionListActivity;
import com.ihighest.app.infox.adapter.MySubscriptionListAdapter;
import com.ihighest.app.infox.fragment.Nj_Fragment_new.ReflashBroadcast;
import com.ihighest.app.infox.tools.CheckNetWork;

/**
 * 订阅界面
 * 
 * @author lkx Created at 2015-10-7 下午5:10:25
 * @version 1.0
 */
public class SubscriptionFragment extends Fragment {
	private PullToRefreshListView subscriptionListview;
	private MySubscriptionListAdapter adapter;
	private Context context;
	String text;
	String channel_id;
	int page = 1;
	private JSONArray array;
	private TextView emptyview;
	private JSONArray moreArray;
	private int isFirst = 0;// 0表示第一次
	private ReflashBroadcast reflashBroadcast;

	public SubscriptionFragment(Context context) {
		this.context = context;
	}

	@Override
	public void onAttach(Activity activity) {
		this.context = activity;
		super.onAttach(activity);
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		this.context = getActivity();
		super.onCreate(savedInstanceState);
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		Bundle args = getArguments();
		text = args != null ? args.getString("text") : "";
		channel_id = args != null ? args.getString("id") : "";
		if (isVisibleToUser) {
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
				if (isFirst == 1) {
					array = new JSONArray();
					adapter = new MySubscriptionListAdapter(getActivity(), array);
					emptyview.setText("暂无数据");
				}

			} else {
				page = 1;
				if (isFirst == 1) {
					getData();
				}

			}
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = LayoutInflater.from(getActivity()).inflate(R.layout.infox_fragment_subscription, null);
		subscriptionListview = (PullToRefreshListView) view.findViewById(R.id.mySubscriptionlistView);
		emptyview = new TextView(context);
		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		emptyview.setText("加载中 ...");
		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		emptyview.setVisibility(View.GONE);
		subscriptionListview.setEmptyView(emptyview);
		
		reflashBroadcast = new ReflashBroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Const.REFLASH);
		context.registerReceiver(reflashBroadcast, filter);
		

		view.findViewById(R.id.subscriptionMore).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(context, LoginActivity.class);
					startActivity(intent);

				} else {
					Intent intent = new Intent(getActivity(), SubscriptionListActivity.class);
					intent.putExtra("channelId", channel_id);
					startActivity(intent);
				}
			}
		});
		subscriptionListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// emptyview.setText("加载中...");
				page = 1;
				getData();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// emptyview.setText("加载中...");
				page++;
				getData();
			}

		});
		getData();
		subscriptionListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// item点击事件
				try {
					if (array.getJSONObject(position - 1).getString("type").equals("Columnist")) {
						// 专栏数据
						Intent intent = new Intent(getActivity(), ColumnNameActivity.class);
						intent.putExtra("cid", array.getJSONObject(position - 1).getString("id"));
						intent.putExtra("name", array.getJSONObject(position - 1).getString("title"));
						intent.putExtra("peoplenumber", array.getJSONObject(position - 1).getInt("count"));
						intent.putExtra("imageurl", array.getJSONObject(position - 1).getString("image"));
						intent.putExtra("subscription", array.getJSONObject(position - 1).getString("isSubscribes"));
                         startActivity(intent);
					} else {
						// 企业号数据
						Intent intent = new Intent(getActivity(), CompanyPagesActivity.class);
						intent.putExtra("cid", array.getJSONObject(position - 1).getString("id"));
						intent.putExtra("name", array.getJSONObject(position - 1).getString("title"));
						intent.putExtra("peoplenumber", array.getJSONObject(position - 1).getInt("count"));
						intent.putExtra("imageurl", array.getJSONObject(position - 1).getString("image"));
						intent.putExtra("subscription", array.getJSONObject(position - 1).getString("isSubscribes"));
						intent.putExtra("describe", array.getJSONObject(position - 1).getString("memo"));
						intent.putExtra("phonenumber", array.getJSONObject(position - 1).getString("phone"));
						intent.putExtra("service", array.getJSONObject(position - 1).getString("service"));
						startActivity(intent);
					}
					//ToastKit.showShort(getActivity(), Const.UN_FINISH_ALERT);
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
		return view;

	}

	/**
	 * 将获取到的数据是配到list中
	 * 
	 * @param array
	 * 
	 * @author lkx Created at 2015-10-20 下午8:06:34
	 */
	private void setData(JSONArray array) {
		if (array == null || array.length() == 0) {
			// Toast.makeText(context, "暂无订阅数据", 0).show();
		} else {
			if (page == 1) {

				adapter = new MySubscriptionListAdapter(context, array);
				subscriptionListview.setAdapter(adapter);
			} else {
				adapter.appendData(array);
			}
		}

	}

	@Override
	public void onResume() {
		if (isFirst == 0) {
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {

			} else {

				getData();
			}
		}

		isFirst = 1;
		super.onResume();
	}

	/**
	 * 获取数据
	 * 
	 * 
	 * @author lkx Created at 2015-10-21 下午2:54:06
	 */
	private void getData() {
		if (CheckNetWork.isConnected(context)) {

			Api.get("channel/subscribes", ApiParam.create().addParam("cid", channel_id).addParam("page", page).addParam("type", "me"),
					new ApiCallback(context, true) {

						@Override
						public void handleSuccess(ApiResult result) {
							if (result.getDatas() == null || result.getDatas().length() == 0) {
								if (page == 1) {
									emptyview.setText("暂无数据");
								} else {
									page = page > 1 ? --page : 1;
								}
                                 
							} else {
								if (page == 1) {
									array = result.getDatas();
									setData(array);
								} else {
									try {
										moreArray = AppKit.joinJSONArray(moreArray, result.getDatas());
									} catch (JSONException e) {
										// pass
									}
									setData(moreArray);
								}
							}
							subscriptionListview.onRefreshComplete();
						}

						@Override
						public void handleFailure(Exception e, String msg) {
							Log.e("subscription", msg);
							subscriptionListview.onRefreshComplete();
						}
					}, context);
		} else {
			if (emptyview != null) {
				emptyview.setText("暂无数据");
			}

			ToastKit.showShort(context, "请连接网络");
		}
	}
	
	public class ReflashBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.REFLASH)) {
				page = 1;
				
				getData();

			}

		}

	}
}
